/*
 * @Description: 通用工具类
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-03-30
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2025-04-23
 */
import type { App, Plugin } from 'vue'

import { isObject } from './is'

export const noop = () => {}

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, component as any)
    if (alias) {
      app.config.globalProperties[alias] = component
    }
  }
  return component as T & Plugin
}

/** px 转 vw, 750 是设置的屏幕宽度 单位px */
export const px2vw = (px: number): number => {
  return (window.screen.width / 750) * px
}

/**
 * 深拷贝
 */
export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
  let key: string
  for (key in target) {
    src[key] = isObject(src[key]) ? deepMerge(src[key], target[key]) : (src[key] = target[key])
  }
  return src
}

export function dispatchEventStroage() {
  const signSetItem = localStorage.setItem
  localStorage.setItem = function (key, val) {
    const setEvent = new Event('setItemEvent') as any
    setEvent.key = key
    setEvent.newValue = val
    window.dispatchEvent(setEvent)
    signSetItem.apply(this, [key, val])
  }
}

/**
 * 是否为mock模式
 * @param url 请求连接
 * @returns
 */
export const isMock = (url: string) => url.indexOf('?') > -1 && url.substring(url.indexOf('?') + 1).indexOf('mock') > -1

/**
 * 是否为本机location环境
 * @returns
 */
export const isLocation = () => import.meta.env.VITE_ENV === 'location'

/**
 * 是否为线上development环境
 * @returns
 */
export const isDevelopment = () => import.meta.env.VITE_ENV === 'development'

/**
 * 是否为线上test环境
 * @returns
 */
export const isTest = () => import.meta.env.VITE_ENV === 'test'

/**
 * 是否为线上uat环境
 * @returns
 */
export const isUat = () => import.meta.env.VITE_ENV === 'uat'

/**
 * 是否为线上production环境
 * @returns
 */
export const isProduction = () => import.meta.env.VITE_ENV === 'production'

/**
 * 字节转换
 * @param bytes 字节数
 * @returns
 */
export const formatBytes = (bytes) => {
  const kb = 1024
  const mb = kb * 1024
  const gb = mb * 1024
  if (bytes < kb) return bytes + 'B'
  if (bytes < mb) return (bytes / kb).toFixed(2) + 'KB'
  if (bytes < gb) return (bytes / mb).toFixed(2) + 'MB'
  return (bytes / gb).toFixed(2) + 'GB'
}
